package menudao

import (
	"go-small-shopping/db"
	login_req "go-small-shopping/entity/dto"
	"go-small-shopping/entity/menu"
)

func AllMenus() []*menu.Menu {
	var menus []*menu.Menu
	db.GetBbCon().Find(&menus)
	return menus
}

// 树形结构
func CollapsibleAllMenus() []*login_req.MenuDto {
	allMenus := AllMenus()
	var menus []*login_req.MenuDto
	for _, k := range allMenus {
		menus = append(menus, &login_req.MenuDto{
			Menu:     *k,
			Children: []*login_req.MenuDto{},
		})
	}

	return handleMenusExtend(menus, 0)
}

// 树形结构
func handleMenusExtend(menus []*login_req.MenuDto, pid int64) []*login_req.MenuDto {
	var reuslt []*login_req.MenuDto
	for _, mn := range menus {
		if mn.MenuPid == pid {
			recursionFn(menus, mn)
			reuslt = append(reuslt, mn)
		}
	}
	return reuslt
}

/**
 * 递归列表
 */
func recursionFn(menus []*login_req.MenuDto, entity *login_req.MenuDto) {
	childMenus := getChildList(menus, entity)
	entity.Children = childMenus
	for _, childMn := range childMenus {
		if hasChild(menus, childMn) {
			for _, cmn := range childMenus {
				recursionFn(menus, cmn)
			}
		}
	}
}

/**
 * 获取子节点列表
 */
func getChildList(menus []*login_req.MenuDto, entity *login_req.MenuDto) []*login_req.MenuDto {
	var tlist []*login_req.MenuDto
	for _, mn := range menus {
		if mn.MenuPid == entity.Id {
			tlist = append(tlist, mn)
		}
	}
	return tlist
}

/**
 * 判断是否有子节点
 */
func hasChild(menus []*login_req.MenuDto, entity *login_req.MenuDto) bool {
	return len(getChildList(menus, entity)) > 0
}
